<template>
  <div class="platform-settings">
    <div class="page-header">
      <h2>平台设置</h2>
      <p>管理平台客服信息和联系方式</p>
    </div>

    <el-card class="settings-card" shadow="never" v-loading="loading">
      <template #header>
        <span>客服信息配置</span>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item label="客服微信号" prop="wechat">
          <el-input
            v-model="formData.wechat"
            placeholder="请输入客服微信号"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="微信二维码" prop="qrcode">
          <div class="qrcode-upload">
            <el-upload
              v-model:file-list="qrcodeFileList"
              :action="API_CONFIG.UPLOAD_IMAGE_URL"
              list-type="picture-card"
              :headers="uploadHeaders"
              :on-success="handleQrcodeUploadSuccess"
              :on-error="handleQrcodeUploadError"
              :on-remove="handleQrcodeRemove"
              :before-upload="beforeQrcodeUpload"
              :limit="1"
              accept="image/*"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">
                  支持 jpg/png/gif 格式，单张图片不超过 2MB
                </div>
              </template>
            </el-upload>
            <el-form-item label="图片URL" style="margin-top: 16px;">
              <el-input
                v-model="formData.qrcode"
                placeholder="上传图片后自动填充，也可手动输入"
                readonly
                style="width: 400px"
              />
            </el-form-item>
          </div>
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入联系电话"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">
            <el-icon><Check /></el-icon>
            保存设置
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 短信模板配置 -->
    <el-card class="settings-card" shadow="never" v-loading="smsLoading" style="margin-top: 20px">
      <template #header>
        <span>短信模板配置</span>
      </template>

      <el-form
        ref="smsFormRef"
        :model="smsFormData"
        :rules="smsFormRules"
        label-width="120px"
        style="max-width: 800px"
      >
        <el-form-item label="订单通知模板" prop="orderTemplate">
          <el-input
            v-model="smsFormData.orderTemplate"
            type="textarea"
            :rows="4"
            placeholder="请输入订单通知短信模板，支持变量：{订单号}、{车牌号}、{停车场名称}、{开始时间}、{结束时间}、{费用}"
            maxlength="500"
            show-word-limit
          />
          <div class="template-tip">
            <p><strong>默认模板：</strong></p>
            <p>【省米停车】尊敬的用户，您的订单{订单号}已创建成功，车牌号：{车牌号}，停车场：{停车场名称}，停车时间：{开始时间}-{结束时间}，费用：{费用}元，请准时入场。如有疑问请联系客服。</p>
          </div>
        </el-form-item>

        <el-form-item label="优惠券通知模板" prop="couponTemplate">
          <el-input
            v-model="smsFormData.couponTemplate"
            type="textarea"
            :rows="3"
            placeholder="请输入优惠券到账通知短信模板，支持变量：{优惠券名称}、{有效期}"
            maxlength="300"
            show-word-limit
          />
          <div class="template-tip">
            <p><strong>默认模板：</strong></p>
            <p>【省米停车】恭喜您获得优惠券"{优惠券名称}"，有效期至{有效期}，快去使用吧！</p>
          </div>
        </el-form-item>

        <el-form-item label="系统通知模板" prop="systemTemplate">
          <el-input
            v-model="smsFormData.systemTemplate"
            type="textarea"
            :rows="3"
            placeholder="请输入系统通知短信模板前缀"
            maxlength="100"
            show-word-limit
          />
          <div class="template-tip">
            <p><strong>说明：</strong>系统通知模板为固定前缀，实际通知内容会追加在后面</p>
            <p><strong>默认模板：</strong>【省米停车】</p>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSaveSms" :loading="smsSaveLoading">
            <el-icon><Check /></el-icon>
            保存短信模板
          </el-button>
          <el-button @click="handleResetSms">
            <el-icon><Refresh /></el-icon>
            重置模板
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 短信服务商配置 -->
    <el-card class="settings-card" shadow="never" v-loading="providerLoading" style="margin-top: 20px">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>短信服务商配置</span>
          <el-switch
            v-model="smsEnabled"
            @change="handleSmsEnabledChange"
            active-text="启用"
            inactive-text="禁用"
            :loading="smsEnabledLoading"
          />
        </div>
      </template>

      <el-form
        ref="providerFormRef"
        :model="providerFormData"
        :rules="providerFormRules"
        label-width="120px"
        style="max-width: 800px"
        :disabled="!smsEnabled"
      >
        <el-form-item label="服务商类型" prop="providerType">
          <el-select
            v-model="providerFormData.providerType"
            placeholder="请选择短信服务商"
            style="width: 200px"
            @change="handleProviderTypeChange"
          >
            <el-option label="阿里云短信" value="aliyun" />
            <el-option label="腾讯云短信" value="tencent" />
          </el-select>
        </el-form-item>

        <!-- 阿里云配置 -->
        <template v-if="providerFormData.providerType === 'aliyun'">
          <el-form-item label="AccessKey ID" prop="accessKeyId">
            <el-input
              v-model="providerFormData.accessKeyId"
              placeholder="请输入阿里云 AccessKey ID"
              maxlength="100"
              show-word-limit
              style="width: 400px"
            />
          </el-form-item>

          <el-form-item label="AccessKey Secret" prop="accessKeySecret">
            <el-input
              v-model="providerFormData.accessKeySecret"
              type="password"
              placeholder="请输入阿里云 AccessKey Secret"
              maxlength="100"
              show-word-limit
              style="width: 400px"
              show-password
            />
          </el-form-item>

          <el-form-item label="短信签名" prop="signName">
            <el-input
              v-model="providerFormData.signName"
              placeholder="请输入短信签名，如：省米停车"
              maxlength="50"
              show-word-limit
              style="width: 300px"
            />
          </el-form-item>

          <el-form-item label="模板代码" prop="templateCode">
            <el-input
              v-model="providerFormData.templateCode"
              placeholder="请输入阿里云短信模板代码，如：SMS_323825475"
              maxlength="50"
              show-word-limit
              style="width: 300px"
            />
            <div class="template-tip">
              <p><strong>说明：</strong>请使用通知类型的短信模板，验证码类型模板不支持中文参数</p>
            </div>
          </el-form-item>
        </template>

        <!-- 腾讯云配置 -->
        <template v-if="providerFormData.providerType === 'tencent'">
          <el-form-item label="SecretId" prop="secretId">
            <el-input
              v-model="providerFormData.secretId"
              placeholder="请输入腾讯云 SecretId"
              maxlength="100"
              show-word-limit
              style="width: 400px"
            />
          </el-form-item>

          <el-form-item label="SecretKey" prop="secretKey">
            <el-input
              v-model="providerFormData.secretKey"
              type="password"
              placeholder="请输入腾讯云 SecretKey"
              maxlength="100"
              show-word-limit
              style="width: 400px"
              show-password
            />
          </el-form-item>

          <el-form-item label="短信签名" prop="signName">
            <el-input
              v-model="providerFormData.signName"
              placeholder="请输入短信签名，如：省米停车"
              maxlength="50"
              show-word-limit
              style="width: 300px"
            />
          </el-form-item>

          <el-form-item label="应用ID" prop="appId">
            <el-input
              v-model="providerFormData.appId"
              placeholder="请输入腾讯云短信应用ID"
              maxlength="50"
              show-word-limit
              style="width: 300px"
            />
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSaveProvider" :loading="providerSaveLoading" :disabled="!smsEnabled">
            <el-icon><Check /></el-icon>
            保存配置
          </el-button>
          <el-button @click="handleResetProvider" :disabled="!smsEnabled">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleTestSms" :loading="testSmsLoading" :disabled="!smsEnabled">
            <el-icon><Picture /></el-icon>
            发送测试短信
          </el-button>
        </el-form-item>

        <el-form-item label="测试手机号" v-if="showTestPhone">
          <el-input
            v-model="testPhoneNumber"
            placeholder="请输入测试手机号"
            maxlength="11"
            style="width: 200px"
          />
          <el-button type="primary" @click="sendTestSms" :loading="testSmsLoading" style="margin-left: 10px">
            发送
          </el-button>
          <el-button @click="showTestPhone = false">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 邮件配置 -->
    <el-card class="settings-card" shadow="never" v-loading="emailLoading" style="margin-top: 20px">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>邮件通知配置</span>
          <el-switch
            v-model="emailEnabled"
            @change="handleEmailEnabledChange"
            active-text="启用"
            inactive-text="禁用"
            :loading="emailEnabledLoading"
          />
        </div>
      </template>

      <el-form
        ref="emailFormRef"
        :model="emailFormData"
        :rules="emailFormRules"
        label-width="120px"
        style="max-width: 800px"
        :disabled="!emailEnabled"
      >
        <el-form-item label="SMTP服务器" prop="host">
          <el-input
            v-model="emailFormData.host"
            placeholder="请输入SMTP服务器地址，如：smtp.163.com"
            maxlength="100"
            show-word-limit
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="SMTP端口" prop="port">
          <el-input-number
            v-model="emailFormData.port"
            :min="1"
            :max="65535"
            placeholder="请输入端口号"
            style="width: 150px"
          />
          <div class="template-tip" style="margin-top: 8px;">
            <p><strong>常用端口：</strong></p>
            <p>465 (SSL加密，推荐) | 587 (STARTTLS) | 25 (非加密)</p>
          </div>
        </el-form-item>

        <el-form-item label="邮箱账号" prop="user">
          <el-input
            v-model="emailFormData.user"
            placeholder="请输入发送邮件的邮箱账号"
            maxlength="100"
            show-word-limit
            style="width: 300px"
          />
        </el-form-item>

        <el-form-item label="邮箱密码" prop="pass">
          <el-input
            v-model="emailFormData.pass"
            type="password"
            placeholder="请输入邮箱授权密码（非登录密码）"
            maxlength="100"
            show-word-limit
            style="width: 300px"
            show-password
          />
          <div class="template-tip" style="margin-top: 8px;">
            <p><strong>注意：</strong></p>
            <p>163邮箱需要使用客户端授权密码，不是登录密码</p>
            <p>请在163邮箱设置中开启SMTP服务并获取授权密码</p>
          </div>
        </el-form-item>

        <el-form-item label="邮件模板" prop="template">
          <el-input
            v-model="emailFormData.template"
            type="textarea"
            :rows="8"
            placeholder="请输入订单通知邮件模板，支持变量：{订单号}、{车牌号}、{停车场名称}、{用户昵称}、{用户手机}、{开始时间}、{结束时间}、{费用}、{创建时间}"
            maxlength="2000"
            show-word-limit
          />
          <div class="template-tip">
            <p><strong>默认模板：</strong></p>
            <p>【省米停车系统】新订单通知<br><br>
            尊敬的停车场管理员，您好！<br><br>
            您管理的停车场"{停车场名称}"收到一个新的停车订单，详情如下：<br><br>
            订单信息：<br>
            - 订单号：{订单号}<br>
            - 车牌号：{车牌号}<br>
            - 用户昵称：{用户昵称}<br>
            - 用户手机：{用户手机}<br><br>
            停车时间：<br>
            - 计划入场时间：{开始时间}<br>
            - 计划出场时间：{结束时间}<br><br>
            费用信息：<br>
            - 停车费用：{费用}元<br><br>
            订单创建时间：{创建时间}<br><br>
            请及时关注订单状态，确保为用户提供优质的停车服务。</p>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSaveEmail" :loading="emailSaveLoading" :disabled="!emailEnabled">
            <el-icon><Check /></el-icon>
            保存邮件配置
          </el-button>
          <el-button @click="handleResetEmail" :disabled="!emailEnabled">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleTestEmail" :loading="testEmailLoading" :disabled="!emailEnabled">
            <el-icon><Picture /></el-icon>
            发送测试邮件
          </el-button>
        </el-form-item>

        <el-form-item label="测试邮箱" v-if="showTestEmail">
          <el-input
            v-model="testEmailAddress"
            placeholder="请输入测试邮箱地址"
            maxlength="100"
            style="width: 300px"
          />
          <el-button type="primary" @click="sendTestEmail" :loading="testEmailLoading" style="margin-left: 10px">
            发送
          </el-button>
          <el-button @click="showTestEmail = false">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Picture, Check, Refresh, Plus } from '@element-plus/icons-vue'
import { getSystemConfig, updateSystemConfig } from '@/api/systemConfig'
import { useUserStore } from '@/stores/user'
import { API_CONFIG } from '@/config'

// 响应式数据
const loading = ref(false)
const saveLoading = ref(false)
const smsLoading = ref(false)
const smsSaveLoading = ref(false)
const providerLoading = ref(false)
const providerSaveLoading = ref(false)
const smsEnabledLoading = ref(false)
const testSmsLoading = ref(false)
const showTestPhone = ref(false)
const testPhoneNumber = ref('')
const smsEnabled = ref(false)

// 邮件相关响应式数据
const emailLoading = ref(false)
const emailSaveLoading = ref(false)
const emailEnabledLoading = ref(false)
const testEmailLoading = ref(false)
const showTestEmail = ref(false)
const testEmailAddress = ref('')
const emailEnabled = ref(false)

// 表单引用和数据
const formRef = ref<FormInstance>()
const smsFormRef = ref<FormInstance>()
const providerFormRef = ref<FormInstance>()
const emailFormRef = ref<FormInstance>()

const formData = reactive({
  wechat: '',
  qrcode: '',
  phone: ''
})

const originalData = reactive({
  wechat: '',
  qrcode: '',
  phone: ''
})

// 用户store
const userStore = useUserStore()

// 图片上传相关
const qrcodeFileList = ref<any[]>([])

// 上传请求头
const uploadHeaders = {
  'Authorization': `Bearer ${userStore.token}`
}

// 短信模板表单数据
const smsFormData = reactive({
  orderTemplate: '',
  couponTemplate: '',
  systemTemplate: ''
})

const originalSmsData = reactive({
  orderTemplate: '',
  couponTemplate: '',
  systemTemplate: ''
})

// 短信服务商配置表单数据
const providerFormData = reactive({
  providerType: 'aliyun',
  accessKeyId: '',
  accessKeySecret: '',
  secretId: '',
  secretKey: '',
  signName: '省米停车',
  templateCode: '',
  appId: ''
})

const originalProviderData = reactive({
  providerType: 'aliyun',
  accessKeyId: '',
  accessKeySecret: '',
  secretId: '',
  secretKey: '',
  signName: '省米停车',
  templateCode: '',
  appId: ''
})

// 邮件配置表单数据
const emailFormData = reactive({
  host: 'smtp.163.com',
  port: 465,
  user: '',
  pass: '',
  template: ''
})

const originalEmailData = reactive({
  host: 'smtp.163.com',
  port: 465,
  user: '',
  pass: '',
  template: ''
})

// 表单验证规则
const formRules: FormRules = {
  wechat: [
    { required: true, message: '请输入客服微信号', trigger: 'blur' },
    { min: 1, max: 50, message: '微信号长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 短信模板验证规则
const smsFormRules: FormRules = {
  orderTemplate: [
    { required: true, message: '请输入订单通知模板', trigger: 'blur' },
    { min: 10, max: 500, message: '模板长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  couponTemplate: [
    { required: true, message: '请输入优惠券通知模板', trigger: 'blur' },
    { min: 10, max: 300, message: '模板长度在 10 到 300 个字符', trigger: 'blur' }
  ],
  systemTemplate: [
    { required: true, message: '请输入系统通知模板', trigger: 'blur' },
    { min: 2, max: 100, message: '模板长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}

// 短信服务商配置验证规则
const providerFormRules: FormRules = {
  providerType: [
    { required: true, message: '请选择服务商类型', trigger: 'change' }
  ],
  accessKeyId: [
    { required: true, message: '请输入 AccessKey ID', trigger: 'blur' },
    { min: 10, max: 100, message: 'AccessKey ID 长度在 10 到 100 个字符', trigger: 'blur' }
  ],
  accessKeySecret: [
    { required: true, message: '请输入 AccessKey Secret', trigger: 'blur' },
    { min: 10, max: 100, message: 'AccessKey Secret 长度在 10 到 100 个字符', trigger: 'blur' }
  ],
  secretId: [
    { required: true, message: '请输入 SecretId', trigger: 'blur' },
    { min: 10, max: 100, message: 'SecretId 长度在 10 到 100 个字符', trigger: 'blur' }
  ],
  secretKey: [
    { required: true, message: '请输入 SecretKey', trigger: 'blur' },
    { min: 10, max: 100, message: 'SecretKey 长度在 10 到 100 个字符', trigger: 'blur' }
  ],
  signName: [
    { required: true, message: '请输入短信签名', trigger: 'blur' },
    { min: 2, max: 50, message: '短信签名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  templateCode: [
    { required: true, message: '请输入阿里云短信模板代码', trigger: 'blur' },
    { pattern: /^SMS_\d+$/, message: '模板代码格式应为 SMS_xxxxxxx', trigger: 'blur' }
  ],
  appId: [
    { required: true, message: '请输入应用ID', trigger: 'blur' },
    { min: 5, max: 50, message: '应用ID长度在 5 到 50 个字符', trigger: 'blur' }
  ]
}

// 邮件配置验证规则
const emailFormRules: FormRules = {
  host: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' },
    { min: 5, max: 100, message: 'SMTP服务器地址长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  port: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口号必须在 1 到 65535 之间', trigger: 'blur' }
  ],
  user: [
    { required: true, message: '请输入邮箱账号', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  pass: [
    { required: true, message: '请输入邮箱密码', trigger: 'blur' },
    { min: 6, max: 100, message: '密码长度在 6 到 100 个字符', trigger: 'blur' }
  ],
  template: [
    { required: true, message: '请输入邮件模板', trigger: 'blur' },
    { min: 50, max: 2000, message: '模板长度在 50 到 2000 个字符', trigger: 'blur' }
  ]
}

/**
 * 获取配置数据
 */
const fetchConfigs = async () => {
  try {
    loading.value = true

    // 并行获取三个配置项
    const [wechatRes, qrcodeRes, phoneRes] = await Promise.allSettled([
      getSystemConfig('customer_service_wechat'),
      getSystemConfig('customer_service_qrcode'),
      getSystemConfig('customer_service_phone')
    ])

    // 处理微信号
    if (wechatRes.status === 'fulfilled' && wechatRes.value.success) {
      formData.wechat = wechatRes.value.data.config_value
      originalData.wechat = wechatRes.value.data.config_value
    }

    // 处理二维码
    if (qrcodeRes.status === 'fulfilled' && qrcodeRes.value.success) {
      formData.qrcode = qrcodeRes.value.data.config_value
      originalData.qrcode = qrcodeRes.value.data.config_value

      // 如果有二维码URL，设置文件列表用于显示
      if (formData.qrcode) {
        qrcodeFileList.value = [{
          uid: `qrcode_${Date.now()}`,
          name: 'qrcode.jpg',
          status: 'done',
          url: formData.qrcode.startsWith('/uploads/') ? `${API_CONFIG.SERVER_URL}${formData.qrcode}` : formData.qrcode,
          originalUrl: formData.qrcode
        }]
      }
    }

    // 处理电话
    if (phoneRes.status === 'fulfilled' && phoneRes.value.success) {
      formData.phone = phoneRes.value.data.config_value
      originalData.phone = phoneRes.value.data.config_value
    }

  } catch (error) {
    console.error('获取配置错误:', error)
    ElMessage.error('获取配置失败')
  } finally {
    loading.value = false
  }
}

/**
 * 获取短信模板配置
 */
const fetchSmsConfigs = async () => {
  try {
    smsLoading.value = true

    // 并行获取短信模板配置项
    const [orderRes, couponRes, systemRes] = await Promise.allSettled([
      getSystemConfig('sms_order_template'),
      getSystemConfig('sms_coupon_template'),
      getSystemConfig('sms_system_template')
    ])

    // 处理订单通知模板
    if (orderRes.status === 'fulfilled' && orderRes.value.success) {
      smsFormData.orderTemplate = orderRes.value.data.config_value
      originalSmsData.orderTemplate = orderRes.value.data.config_value
    } else {
      // 设置默认模板
      const defaultOrderTemplate = '【省米停车】尊敬的用户，您的订单{订单号}已创建成功，车牌号：{车牌号}，停车场：{停车场名称}，停车时间：{开始时间}-{结束时间}，费用：{费用}元，请准时入场。如有疑问请联系客服。'
      smsFormData.orderTemplate = defaultOrderTemplate
      originalSmsData.orderTemplate = defaultOrderTemplate
    }

    // 处理优惠券通知模板
    if (couponRes.status === 'fulfilled' && couponRes.value.success) {
      smsFormData.couponTemplate = couponRes.value.data.config_value
      originalSmsData.couponTemplate = couponRes.value.data.config_value
    } else {
      // 设置默认模板
      const defaultCouponTemplate = '【省米停车】恭喜您获得优惠券"{优惠券名称}"，有效期至{有效期}，快去使用吧！'
      smsFormData.couponTemplate = defaultCouponTemplate
      originalSmsData.couponTemplate = defaultCouponTemplate
    }

    // 处理系统通知模板
    if (systemRes.status === 'fulfilled' && systemRes.value.success) {
      smsFormData.systemTemplate = systemRes.value.data.config_value
      originalSmsData.systemTemplate = systemRes.value.data.config_value
    } else {
      // 设置默认模板
      const defaultSystemTemplate = '【省米停车】'
      smsFormData.systemTemplate = defaultSystemTemplate
      originalSmsData.systemTemplate = defaultSystemTemplate
    }

  } catch (error) {
    console.error('获取短信模板配置错误:', error)
    ElMessage.error('获取短信模板配置失败')
  } finally {
    smsLoading.value = false
  }
}

/**
 * 获取邮件配置
 */
const fetchEmailConfigs = async () => {
  try {
    emailLoading.value = true

    // 并行获取邮件配置项
    const [enabledRes, smtpRes, templateRes] = await Promise.allSettled([
      getSystemConfig('email_enabled'),
      getSystemConfig('email_smtp_config'),
      getSystemConfig('email_order_template')
    ])

    // 处理启用状态
    if (enabledRes.status === 'fulfilled' && enabledRes.value.success) {
      emailEnabled.value = enabledRes.value.data.config_value === 'true'
    } else {
      emailEnabled.value = false
    }

    // 处理SMTP配置
    if (smtpRes.status === 'fulfilled' && smtpRes.value.success) {
      try {
        const smtpConfig = JSON.parse(smtpRes.value.data.config_value)
        emailFormData.host = smtpConfig.host || 'smtp.163.com'
        emailFormData.port = smtpConfig.port || 465
        emailFormData.user = smtpConfig.user || ''
        emailFormData.pass = smtpConfig.pass || ''

        // 更新原始数据
        originalEmailData.host = emailFormData.host
        originalEmailData.port = emailFormData.port
        originalEmailData.user = emailFormData.user
        originalEmailData.pass = emailFormData.pass
      } catch (error) {
        console.error('解析SMTP配置失败:', error)
      }
    }

    // 处理邮件模板
    if (templateRes.status === 'fulfilled' && templateRes.value.success) {
      emailFormData.template = templateRes.value.data.config_value
      originalEmailData.template = templateRes.value.data.config_value
    } else {
      // 设置默认模板
      const defaultTemplate = `【省米停车系统】新订单通知

尊敬的停车场管理员，您好！

您管理的停车场"{停车场名称}"收到一个新的停车订单，详情如下：

订单信息：
- 订单号：{订单号}
- 车牌号：{车牌号}
- 用户昵称：{用户昵称}
- 用户手机：{用户手机}

停车时间：
- 计划入场时间：{开始时间}
- 计划出场时间：{结束时间}

费用信息：
- 停车费用：{费用}元

订单创建时间：{创建时间}

请及时关注订单状态，确保为用户提供优质的停车服务。

如有疑问，请联系系统管理员。

此邮件由系统自动发送，请勿回复。`
      emailFormData.template = defaultTemplate
      originalEmailData.template = defaultTemplate
    }

  } catch (error) {
    console.error('获取邮件配置错误:', error)
    ElMessage.error('获取邮件配置失败')
  } finally {
    emailLoading.value = false
  }
}

/**
 * 保存设置
 */
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saveLoading.value = true

    // 准备配置数据
    const configs = [
      {
        config_key: 'customer_service_wechat',
        config_value: formData.wechat.trim(),
        description: '客服微信号'
      },
      {
        config_key: 'customer_service_qrcode',
        config_value: formData.qrcode.trim(),
        description: '客服微信二维码'
      },
      {
        config_key: 'customer_service_phone',
        config_value: formData.phone.trim(),
        description: '客服联系电话'
      }
    ]

    // 并行保存所有配置
    const savePromises = configs.map(config => updateSystemConfig(config))
    const results = await Promise.allSettled(savePromises)

    // 检查保存结果
    const failedCount = results.filter(result =>
      result.status === 'rejected' ||
      (result.status === 'fulfilled' && !result.value.success)
    ).length

    if (failedCount === 0) {
      ElMessage.success('保存成功')
      // 更新原始数据
      originalData.wechat = formData.wechat
      originalData.qrcode = formData.qrcode
      originalData.phone = formData.phone
    } else {
      ElMessage.error(`保存失败，有 ${failedCount} 项配置保存失败`)
    }

  } catch (error) {
    console.error('保存设置错误:', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

/**
 * 重置表单
 */
const handleReset = () => {
  formData.wechat = originalData.wechat
  formData.qrcode = originalData.qrcode
  formData.phone = originalData.phone

  // 重置二维码文件列表
  if (originalData.qrcode) {
    qrcodeFileList.value = [{
      uid: `qrcode_${Date.now()}`,
      name: 'qrcode.jpg',
      status: 'done',
      url: originalData.qrcode.startsWith('/uploads/') ? `${API_CONFIG.SERVER_URL}${originalData.qrcode}` : originalData.qrcode,
      originalUrl: originalData.qrcode
    }]
  } else {
    qrcodeFileList.value = []
  }

  formRef.value?.clearValidate()
  ElMessage.info('已重置为上次保存的配置')
}

/**
 * 二维码上传前检查
 */
const beforeQrcodeUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/**
 * 二维码上传成功回调
 */
const handleQrcodeUploadSuccess = (response: any, file: any) => {
  if (response.success && response.data?.url) {
    // 更新二维码URL
    formData.qrcode = response.data.url

    // 更新文件列表
    const fileIndex = qrcodeFileList.value.findIndex(item => item.uid === file.uid)
    if (fileIndex !== -1) {
      qrcodeFileList.value[fileIndex].url = `${API_CONFIG.SERVER_URL}${response.data.url}`
      qrcodeFileList.value[fileIndex].status = 'done'
      qrcodeFileList.value[fileIndex].originalUrl = response.data.url
    }

    ElMessage.success('二维码上传成功')
  } else {
    ElMessage.error(response.message || '二维码上传失败')
  }
}

/**
 * 二维码上传失败回调
 */
const handleQrcodeUploadError = (error: any) => {
  console.error('二维码上传失败:', error)
  ElMessage.error('二维码上传失败，请重试')
}

/**
 * 二维码删除回调
 */
const handleQrcodeRemove = (file: any) => {
  // 清空二维码URL
  formData.qrcode = ''
  // 清空文件列表
  qrcodeFileList.value = []
}

/**
 * 保存短信模板
 */
const handleSaveSms = async () => {
  if (!smsFormRef.value) return

  try {
    await smsFormRef.value.validate()
    smsSaveLoading.value = true

    // 准备短信模板配置数据
    const smsConfigs = [
      {
        config_key: 'sms_order_template',
        config_value: smsFormData.orderTemplate.trim(),
        description: '订单通知短信模板'
      },
      {
        config_key: 'sms_coupon_template',
        config_value: smsFormData.couponTemplate.trim(),
        description: '优惠券通知短信模板'
      },
      {
        config_key: 'sms_system_template',
        config_value: smsFormData.systemTemplate.trim(),
        description: '系统通知短信模板'
      }
    ]

    // 并行保存所有配置
    const results = await Promise.allSettled(
      smsConfigs.map(config => updateSystemConfig(config))
    )

    // 检查保存结果
    const failedCount = results.filter(result =>
      result.status === 'rejected' ||
      (result.status === 'fulfilled' && !result.value.success)
    ).length

    if (failedCount === 0) {
      ElMessage.success('短信模板保存成功')
      // 更新原始数据
      originalSmsData.orderTemplate = smsFormData.orderTemplate
      originalSmsData.couponTemplate = smsFormData.couponTemplate
      originalSmsData.systemTemplate = smsFormData.systemTemplate
    } else {
      ElMessage.error(`保存失败，有 ${failedCount} 项模板保存失败`)
    }

  } catch (error) {
    console.error('保存短信模板错误:', error)
    ElMessage.error('保存短信模板失败')
  } finally {
    smsSaveLoading.value = false
  }
}

/**
 * 重置短信模板
 */
const handleResetSms = () => {
  smsFormData.orderTemplate = originalSmsData.orderTemplate
  smsFormData.couponTemplate = originalSmsData.couponTemplate
  smsFormData.systemTemplate = originalSmsData.systemTemplate
  smsFormRef.value?.clearValidate()
  ElMessage.info('已重置为上次保存的模板')
}

/**
 * 获取短信服务商配置
 */
const fetchProviderConfigs = async () => {
  try {
    providerLoading.value = true

    // 并行获取配置项
    const [enabledRes, typeRes, configRes, templateCodeRes] = await Promise.allSettled([
      getSystemConfig('sms_enabled'),
      getSystemConfig('sms_provider_type'),
      getSystemConfig('sms_provider_config'),
      getSystemConfig('sms_aliyun_template_code')
    ])

    // 处理启用状态
    if (enabledRes.status === 'fulfilled' && enabledRes.value.success) {
      smsEnabled.value = enabledRes.value.data.config_value === 'true'
    } else {
      smsEnabled.value = false
    }

    // 处理服务商类型
    if (typeRes.status === 'fulfilled' && typeRes.value.success) {
      providerFormData.providerType = typeRes.value.data.config_value || 'aliyun'
      originalProviderData.providerType = providerFormData.providerType
    }

    // 处理服务商配置
    if (configRes.status === 'fulfilled' && configRes.value.success) {
      try {
        const config = JSON.parse(configRes.value.data.config_value)

        // 根据服务商类型设置配置
        if (providerFormData.providerType === 'aliyun') {
          providerFormData.accessKeyId = config.accessKeyId || ''
          providerFormData.accessKeySecret = config.accessKeySecret || ''
          providerFormData.signName = config.signName || '省米停车'

          originalProviderData.accessKeyId = providerFormData.accessKeyId
          originalProviderData.accessKeySecret = providerFormData.accessKeySecret
          originalProviderData.signName = providerFormData.signName
        } else if (providerFormData.providerType === 'tencent') {
          providerFormData.secretId = config.secretId || ''
          providerFormData.secretKey = config.secretKey || ''
          providerFormData.signName = config.signName || '省米停车'
          providerFormData.appId = config.appId || ''

          originalProviderData.secretId = providerFormData.secretId
          originalProviderData.secretKey = providerFormData.secretKey
          originalProviderData.signName = providerFormData.signName
          originalProviderData.appId = providerFormData.appId
        }
      } catch (error) {
        console.error('解析服务商配置失败:', error)
      }
    }

    // 处理阿里云模板代码
    if (templateCodeRes.status === 'fulfilled' && templateCodeRes.value.success) {
      providerFormData.templateCode = templateCodeRes.value.data.config_value || ''
      originalProviderData.templateCode = providerFormData.templateCode
    }

  } catch (error) {
    console.error('获取短信服务商配置错误:', error)
    ElMessage.error('获取短信服务商配置失败')
  } finally {
    providerLoading.value = false
  }
}

/**
 * 短信启用状态变更
 */
const handleSmsEnabledChange = async (enabled: boolean) => {
  try {
    smsEnabledLoading.value = true

    const result = await updateSystemConfig({
      config_key: 'sms_enabled',
      config_value: enabled ? 'true' : 'false',
      description: '是否启用短信功能'
    })

    if (result.success) {
      ElMessage.success(enabled ? '短信功能已启用' : '短信功能已禁用')
    } else {
      // 恢复原状态
      smsEnabled.value = !enabled
      ElMessage.error('更新短信功能状态失败')
    }
  } catch (error) {
    console.error('更新短信功能状态错误:', error)
    smsEnabled.value = !enabled
    ElMessage.error('更新短信功能状态失败')
  } finally {
    smsEnabledLoading.value = false
  }
}

/**
 * 服务商类型变更
 */
const handleProviderTypeChange = (type: string) => {
  // 清空配置数据
  providerFormData.accessKeyId = ''
  providerFormData.accessKeySecret = ''
  providerFormData.secretId = ''
  providerFormData.secretKey = ''
  providerFormData.signName = '省米停车'
  providerFormData.appId = ''

  // 清除验证错误
  providerFormRef.value?.clearValidate()
}

/**
 * 保存服务商配置
 */
const handleSaveProvider = async () => {
  if (!providerFormRef.value) return

  try {
    await providerFormRef.value.validate()
    providerSaveLoading.value = true

    // 构建配置对象
    const configData: any = {
      signName: providerFormData.signName.trim()
    }

    if (providerFormData.providerType === 'aliyun') {
      configData.accessKeyId = providerFormData.accessKeyId.trim()
      configData.accessKeySecret = providerFormData.accessKeySecret.trim()
    } else if (providerFormData.providerType === 'tencent') {
      configData.secretId = providerFormData.secretId.trim()
      configData.secretKey = providerFormData.secretKey.trim()
      configData.appId = providerFormData.appId.trim()
    }

    // 准备配置数据
    const configs = [
      {
        config_key: 'sms_provider_type',
        config_value: providerFormData.providerType,
        description: '短信服务商类型'
      },
      {
        config_key: 'sms_provider_config',
        config_value: JSON.stringify(configData),
        description: '短信服务商配置'
      }
    ]

    // 如果是阿里云，还需要保存模板代码
    if (providerFormData.providerType === 'aliyun' && providerFormData.templateCode.trim()) {
      configs.push({
        config_key: 'sms_aliyun_template_code',
        config_value: providerFormData.templateCode.trim(),
        description: '阿里云短信模板代码'
      })
    }

    // 并行保存配置
    const results = await Promise.allSettled(
      configs.map(config => updateSystemConfig(config))
    )

    // 检查保存结果
    const failedCount = results.filter(result =>
      result.status === 'rejected' ||
      (result.status === 'fulfilled' && !result.value.success)
    ).length

    if (failedCount === 0) {
      ElMessage.success('短信服务商配置保存成功')
      // 更新原始数据
      Object.assign(originalProviderData, providerFormData)
    } else {
      ElMessage.error('保存失败，请检查配置信息')
    }

  } catch (error) {
    console.error('保存短信服务商配置错误:', error)
    ElMessage.error('保存短信服务商配置失败')
  } finally {
    providerSaveLoading.value = false
  }
}

/**
 * 重置服务商配置
 */
const handleResetProvider = () => {
  Object.assign(providerFormData, originalProviderData)
  providerFormRef.value?.clearValidate()
  ElMessage.info('已重置为上次保存的配置')
}

/**
 * 测试短信发送
 */
const handleTestSms = () => {
  showTestPhone.value = true
  testPhoneNumber.value = ''
}

/**
 * 邮件启用状态变更
 */
const handleEmailEnabledChange = async (enabled: boolean) => {
  try {
    emailEnabledLoading.value = true

    const result = await updateSystemConfig({
      config_key: 'email_enabled',
      config_value: enabled ? 'true' : 'false',
      description: '是否启用邮件功能'
    })

    if (result.success) {
      ElMessage.success(enabled ? '邮件功能已启用' : '邮件功能已禁用')
    } else {
      // 恢复原状态
      emailEnabled.value = !enabled
      ElMessage.error('更新邮件功能状态失败')
    }
  } catch (error) {
    console.error('更新邮件功能状态错误:', error)
    emailEnabled.value = !enabled
    ElMessage.error('更新邮件功能状态失败')
  } finally {
    emailEnabledLoading.value = false
  }
}

/**
 * 保存邮件配置
 */
const handleSaveEmail = async () => {
  if (!emailFormRef.value) return

  try {
    await emailFormRef.value.validate()
    emailSaveLoading.value = true

    // 构建SMTP配置对象
    const smtpConfig = {
      host: emailFormData.host.trim(),
      port: emailFormData.port,
      user: emailFormData.user.trim(),
      pass: emailFormData.pass.trim()
    }

    // 准备配置数据
    const configs = [
      {
        config_key: 'email_smtp_config',
        config_value: JSON.stringify(smtpConfig),
        description: 'SMTP服务器配置'
      },
      {
        config_key: 'email_order_template',
        config_value: emailFormData.template.trim(),
        description: '订单通知邮件模板'
      }
    ]

    // 并行保存配置
    const results = await Promise.allSettled(
      configs.map(config => updateSystemConfig(config))
    )

    // 检查保存结果
    const failedCount = results.filter(result =>
      result.status === 'rejected' ||
      (result.status === 'fulfilled' && !result.value.success)
    ).length

    if (failedCount === 0) {
      ElMessage.success('邮件配置保存成功')
      // 更新原始数据
      Object.assign(originalEmailData, emailFormData)
    } else {
      ElMessage.error('保存失败，请检查配置信息')
    }

  } catch (error) {
    console.error('保存邮件配置错误:', error)
    ElMessage.error('保存邮件配置失败')
  } finally {
    emailSaveLoading.value = false
  }
}

/**
 * 重置邮件配置
 */
const handleResetEmail = () => {
  Object.assign(emailFormData, originalEmailData)
  emailFormRef.value?.clearValidate()
  ElMessage.info('已重置为上次保存的配置')
}

/**
 * 测试邮件发送
 */
const handleTestEmail = () => {
  showTestEmail.value = true
  testEmailAddress.value = ''
}

/**
 * 发送测试邮件
 */
const sendTestEmail = async () => {
  if (!testEmailAddress.value) {
    ElMessage.error('请输入测试邮箱地址')
    return
  }

  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(testEmailAddress.value)) {
    ElMessage.error('请输入正确的邮箱格式')
    return
  }

  try {
    testEmailLoading.value = true

    // 调用后端测试接口
    const response = await fetch('/api/admin/test-email', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userStore.token}`
      },
      body: JSON.stringify({
        email: testEmailAddress.value
      })
    })

    const result = await response.json()

    if (result.success) {
      ElMessage.success('测试邮件发送成功')
      showTestEmail.value = false
      testEmailAddress.value = ''
    } else {
      ElMessage.error(result.message || '测试邮件发送失败')
    }

  } catch (error) {
    console.error('发送测试邮件错误:', error)
    ElMessage.error('发送测试邮件失败')
  } finally {
    testEmailLoading.value = false
  }
}

/**
 * 发送测试短信
 */
const sendTestSms = async () => {
  if (!testPhoneNumber.value) {
    ElMessage.error('请输入测试手机号')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(testPhoneNumber.value)) {
    ElMessage.error('请输入正确的手机号格式')
    return
  }

  try {
    testSmsLoading.value = true

    // 调用后端测试接口
    const response = await fetch('/api/admin/test-sms', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userStore.token}`
      },
      body: JSON.stringify({
        phone: testPhoneNumber.value
      })
    })

    const result = await response.json()

    if (result.success) {
      ElMessage.success('测试短信发送成功')
      showTestPhone.value = false
      testPhoneNumber.value = ''
    } else {
      ElMessage.error(result.message || '测试短信发送失败')
    }

  } catch (error) {
    console.error('发送测试短信错误:', error)
    ElMessage.error('发送测试短信失败')
  } finally {
    testSmsLoading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchConfigs()
  fetchSmsConfigs()
  fetchProviderConfigs()
  fetchEmailConfigs()
})
</script>

<style scoped>
.platform-settings {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.settings-card {
  margin-bottom: 20px;
}

.qrcode-upload {
  width: 100%;
}

.qrcode-preview {
  margin-top: 16px;
  padding: 16px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  text-align: center;
  background-color: #fafafa;
}

.image-slot {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #c0c4cc;
  font-size: 12px;
}

/* 短信模板样式 */
.template-tip {
  margin-top: 8px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.template-tip p {
  margin: 4px 0;
  font-size: 13px;
  line-height: 1.5;
}

.template-tip p:first-child {
  color: #409eff;
  font-weight: 600;
}

.template-tip p:last-child {
  color: #606266;
}
</style>
